﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using MyWebPagesStarterKit;
using System.Text;
using MyWebPagesStarterKit.Controls;

public partial class Administration_EmailTemplates : PageBaseClass
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            FillList();
    }

    private void FillList()
    {
        MailTemplate template = MailTemplate.GetInstance();
        gwTemplates.DataSource = template.Entries;
        gwTemplates.DataBind();
    }

    protected void Action(object sender, CommandEventArgs e)
    {
        if(!string.IsNullOrEmpty(e.CommandArgument.ToString()))
            ViewState["EditID"] = e.CommandArgument.ToString();

        switch (e.CommandName)
        {
            case "tab1":
                gwTemplates.DataSource = null;
                FillList();
                t1.CssClass = "default-tab";
                t2.CssClass = "";
                multiview.SetActiveView(view1);
                break;
            case "tab2":
                if (gwTemplates.SelectedIndex < 0)
                    AddTemplate();
                t1.CssClass = "";
                t2.CssClass = "default-tab";
                multiview.SetActiveView(view2);
                break;
            case "edit_data":
                ViewState["EditID"] = gwTemplates.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString();
                t1.CssClass = "";
                t2.CssClass = "default-tab";
                multiview.SetActiveView(view2);
                EditData(EditID);
                break;
            case "delete_data":
                ViewState["EditID"] = null;
                DeleteData(gwTemplates.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());
                break;
            case "add_data":
                t1.CssClass = "";
                t2.CssClass = "default-tab";
                multiview.SetActiveView(view2);
                AddTemplate();
                break;
            case "save_data":
                string t = null;
                if (ViewState["EditID"] != null)
                    t = EditID;
                SaveTemplate(t);
                break;
        }
    }

    public string EditID
    {
        get { return Convert.ToString(ViewState["EditID"]); }
        set { ViewState["EditID"] = value; }
    }

    private void DeleteData(string id)
    {
        MailTemplate template = MailTemplate.GetInstance();
        DataRow row = template.GetRowFromKey(id);

        string path = Server.MapPath(string.Format("~/App_Data/Templates/{0}/Mail/{1}.config", WebSite.GetInstance().Theme, Convert.ToString(row["TitleUnique"])));
        File.Delete(path);

        template.Entries.Rows.Remove(row);
        template.Entries.AcceptChanges();
        template.SaveData();


        Response.Redirect(Request.RawUrl);
    }

    private void EditData(string id)
    {
        ViewState["EditID"] = id;
        MailTemplate template = MailTemplate.GetInstance();
        DataRow row = template.GetRowFromKey(id);
        txtTitle.Text = Convert.ToString(row["Title"]);
        txtTitleUnique.Text = Convert.ToString(row["TitleUnique"]);
        txtSubject.Text = Convert.ToString(row["Subject"]);
        txtDescription.Text = Convert.ToString(row["Description"]);
        string path = Server.MapPath(string.Format("~/App_Data/Templates/{0}/Mail/{1}.config", WebSite.GetInstance().Theme, Convert.ToString(row["TitleUnique"])));
        TextReader tr = new StreamReader(path);
        txtFileContent.Text = tr.ReadToEnd();
        tr.Close();
    }

    private void AddTemplate()
    {
        ViewState["EditID"] = null;
        txtTitle.Text = string.Empty;
        txtTitleUnique.Text = string.Empty;
        txtSubject.Text = string.Empty;
        txtFileContent.Text = string.Empty;
        txtDescription.Text = string.Empty;
    }

    private void SaveTemplate(string id)
    {
        MailTemplate template = MailTemplate.GetInstance();

        string file;
        litMessage.Text = string.Empty;

        DataRow row = null;
        if (string.IsNullOrEmpty(id))
        {
            file = Server.MapPath(string.Format("~/App_Data/Templates/{0}/Mail/{1}.config", WebSite.GetInstance().Theme, txtTitleUnique.Text));
            if (!File.Exists(file))
            {
                row = template.Entries.NewRow();
                row["Guid"] = Guid.NewGuid();
                template.Entries.Rows.Add(row);
            }
            else
            {
                litMessage.Text = "File already exist.";
                return;
            }
        }
        else
        {
            row = template.GetRowFromKey(id);
        }

        row["Title"] = txtTitle.Text;
        row["TitleUnique"] = txtTitleUnique.Text;
        row["Subject"] = txtSubject.Text;
        row["Description"] = txtDescription.Text;

        row.AcceptChanges();
        template.SaveData();

        try
        {
            

            file = Server.MapPath(string.Format("~/App_Data/Templates/{0}/Mail/{1}.config", WebSite.GetInstance().Theme, txtTitleUnique.Text));
            string path = Server.MapPath(string.Format("~/App_Data/Templates/{0}/Mail/", WebSite.GetInstance().Theme));

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            FileStream s = File.Open(file, FileMode.Create);
            Encoding enc = Encoding.UTF8;

            byte[] filedata = enc.GetBytes(txtFileContent.Text);
            s.Write(filedata, 0, filedata.Length);

            s.Close();
        }
        catch (Exception ex) { Response.Write("Error creating file, check write permissions." + ex.ToString()); }

        EditData(Convert.ToString(row["Guid"]));

    }
}
